package com.ruibang.glass.job.service;


import cn.hutool.core.collection.ListUtil;
import com.ruibang.glass.job.entity.DefectDataSource;
import com.ruibang.glass.job.entity.RQDataSource;
import com.ruibang.glass.job.entity.TimeInterval;
import com.ruibang.glass.job.entity.TotalEquData;
import com.ruibang.glass.job.mapper.TotalEquDataMapper;
import com.ruibang.glass.job.utils.JdbcOperUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class AsyncTotalDataService {

    @Autowired
    private TotalEquDataMapper totalEquDataMapper;


    //产线质量数据
    @Async
    public CompletableFuture<String> asyncTotalData(String prodLine, DefectDataSource defectDataSource, TimeInterval timeInterval) {
        // 这里是异步执行的代码
        System.out.println(prodLine + " panel defect data etl start...");
        List<TotalEquData> list = queryData(prodLine,defectDataSource,timeInterval);
        int totalSize = list.size();
        if(CollectionUtils.isNotEmpty(list)){
                try {
                    long start = System.currentTimeMillis();
                    long init = System.currentTimeMillis();
                    long end ;
                    List<List<TotalEquData>> submitList = ListUtil.split(list, defectDataSource.getBatchInsert());
                    for (List<TotalEquData> elist : submitList)
                    {
                        totalEquDataMapper.insertBatch(elist);
                        end = System.currentTimeMillis();
                        totalSize += elist.size();
                        System.out.println(prodLine + " insert " + elist.size() + "条花费的时间：" + (end - start) + "毫秒 "+((elist.size())/(end - start))+"条/毫秒");
                        Thread.sleep(defectDataSource.getSleepMs());
                        start = System.currentTimeMillis();
                    }
                    end = System.currentTimeMillis();
                    System.out.println(prodLine + " insert " + totalSize + "条共计花费的时间：" + (end - init) + "毫秒 "+((totalSize)/(end - init))+"条/毫秒");

                } catch(Exception e) {
                    e.printStackTrace();
                }
        }
        return CompletableFuture.completedFuture(prodLine + " panel defect data etl successful,total size:" + totalSize);
    }

    private List<TotalEquData> queryData(String prodLine, DefectDataSource defectDataSource,TimeInterval timeInterval){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<TotalEquData> totalEquDataList = new ArrayList<>();
        try {
            conn = JdbcOperUtils.getConnection(defectDataSource,timeInterval,false);

            String sql = MessageFormat.format(defectDataSource.readSqlFile(),
                    prodLine,
                    JdbcOperUtils.getDBDate(timeInterval.getEndTime(),false),
                    timeInterval.getStartTime(),timeInterval.getEndTime());
            if(null == conn)return totalEquDataList;
            System.out.println(prodLine + " panel defect data etl sql:" + sql);
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                TotalEquData equData = TotalEquData.builder()
                        .CustomerPanelId((String)rs.getObject(1))
                        .CustomerBatchId((String) rs.getObject(2))
                        .MachineId((String) rs.getObject(3))
                        .DefectCount((int)rs.getObject(4))
                        .StartTime(((Timestamp)rs.getObject(5)).toLocalDateTime())
                        .DefectId((int)rs.getObject(6))
                        .DefectName((String) rs.getObject(7))
                        .TiltedSizeLengthMM((double)rs.getObject(8))
                        .TiltedSizeWidthMM((double)rs.getObject(9))
                        .MaterialCenterDW((double)rs.getObject(10))
                        .MaterialCenterCW((double)rs.getObject(11))
                        .TiltedSize((double)rs.getObject(12))
                        .TiltedDepth((double)rs.getObject(13))
                        .TiltedDiv((double)rs.getObject(14))
                        .isRead(((long)rs.getObject(15)) == 0 ? false: true)
                        .isFinished(((long)rs.getObject(16)) == 0 ? false: true)
                        .Quality((int)rs.getObject(17))
                        .ManualQuality((int)rs.getObject(18))
                        .comment((String) rs.getObject(19))
                        .productionLine((String) rs.getObject(20))
                        .f8((double)rs.getObject(21))
                        .Camera((int)rs.getObject(22))
                        .sourceDB((String) rs.getObject(23))
                        .MechanicalBoundingBoxWidth((double)rs.getObject(24))
                        .MechanicalBoundingBoxLength((double)rs.getObject(25))
                        .build();
                totalEquDataList.add(equData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JdbcOperUtils.closeResource(conn, ps);
        }
        return totalEquDataList;
    }
}
